import {
  _decorator,
  Component,
  Node,
  EventTouch,
  UITransform,
  Vec3,
  instantiate,
  Prefab,
  Vec2,
  SpriteAtlas,
  resources,
  JsonAsset,
  Asset,
  UIOpacity,
} from 'cc'
import { BagGrilditem } from './BagGrilditem'
import { WeapItem } from './WeapItem'
import { RandomByRange } from '../../Utils/UtilsIndex'
import { DataMgr } from '../../Runtime/GameData'
import { ConfigSelectItemData } from './ConfigSelectItemData'

const { ccclass, property } = _decorator

@ccclass('popupBagUI')
export class popupBagUI extends Component {
  @property(Node)
  bottomBgLayer: Node = null
  @property(Node)
  selectItem: Node = null
  @property(Node)
  occupyNode: Node = null

  @property(Prefab)
  pfBagitem: Prefab = null

  @property(Prefab)
  pfSelectitem: Prefab = null

  @property(SpriteAtlas)
  private m_atlas: SpriteAtlas = null

  @property(Node)
  grildBg: Node = null
  @property(Node)
  diBanBg: Node = null

  private m_itemArr: BagGrilditem[][] = []

  private m_selectItemData: Map<number, ConfigSelectItemData> = new Map()

  private ItemNodeToGrildMap: Map<number, Node> = new Map()
  start() {
    // this.pfBagitem = await ResourceManager.Instance.loadPrefabAsync('Bagitem')
    this.initItemList()
    this.loadResAsync('config/ConfigSelectItemData', JsonAsset).then((res: JsonAsset) => {
      let list = res.json
      for (const key in list) {
        this.m_selectItemData.set(list[key].type, list[key])
      }
      this.createSelectItem()
    })
  }

  private initItemList() {
    for (let i = DataMgr.BagGrid_column; i > 0; i--) {
      for (let j = 1; j <= DataMgr.BagGrid_row; j++) {
        // if (j <= 2 && i <= 2) this.createBagGrild(j, i, this.bottomBgLayer)

        this.createBagGrild(j, i, this.bottomBgLayer)
        // this.createItem(j, i)
      }
    }
  }

  private createBagGrild(x: number, y: number, nodeParent: Node, setColor = false) {
    // 创建物品节点并添加到容器中
    const node: Node = instantiate(this.pfBagitem)
    node.parent = nodeParent
    const com: BagGrilditem = node.getComponent(BagGrilditem)
    com.create(x, y, `item_${x}_${y}`)
    if (setColor) {
      com.setColor()
    }

    node.setPosition(new Vec3((x - 3) * 106, (2 - y) * 106, 0))

    console.log(`item_${x}_${y}`, node.getPosition())
    if (!this.m_itemArr[x - 1]) {
      this.m_itemArr[x - 1] = []
    }
    this.m_itemArr[x - 1].push(com)
  }
  private createSelectItem() {
    for (let i = 0; i < 3; i++) {
      const type = RandomByRange(1, 4)
      let data = this.m_selectItemData.get(type)
      let ItemData = new ConfigSelectItemData()
      ItemData.loadJson(data)
      ItemData.setOtherData(i, this.m_atlas, this.node)

      const node: Node = instantiate(this.pfSelectitem)
      const com: WeapItem = node.getComponent(WeapItem)
      node.parent = this.selectItem

      com.createItem(ItemData)
    }
  }

  // 高亮显示可以放置图形的格子
  highlightGrid(touchPos: Node) {
    let localPos: Vec3 = touchPos.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO)
    const children = this.bottomBgLayer.children
    const compSelectItem = touchPos.getComponent(WeapItem)
    this.isFuWei(localPos, compSelectItem, this.grildBg.children)
    for (let i = 0; i < children.length; i++) {
      const child = children[i]
      let childPosition = child.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO)
      /**判断高亮显示可以放置图形的格子 */
      if (
        childPosition.x < localPos.x &&
        localPos.x < childPosition.x + 106 &&
        childPosition.y < localPos.y &&
        localPos.y < childPosition.y + 106
      ) {
        this.highItem(compSelectItem.getSizeMap(), i, compSelectItem)
      }
    }
  }
  /**判断是否要复位 */
  public isFuWei(localPos: Vec3, compSelectItem: WeapItem, children: Node[]) {
    for (let i = 0; i < children.length; i++) {
      /**判断是否要复位 */
      const child = children[i]
      let childPosition = child.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO)
      if (i === children.length - 1) {
        if (localPos.y > childPosition.y + 106) {
          compSelectItem.fuWei()
        }
        if (localPos.x > childPosition.x + 150) {
          compSelectItem.fuWei()
        }
      }
      if (i === 0) {
        if (localPos.y < childPosition.y - 106 * 2) {
          compSelectItem.fuWei()
        }
        if (localPos.x < childPosition.x - 150) {
          compSelectItem.fuWei()
        }
      }
    }
  }
  public highItem(_arr: number[], _i: number, compSelectItem: WeapItem) {
    compSelectItem.setPosIndex = []
    const children = this.bottomBgLayer.children
    let arr_block = _arr
    let i_node = _i
    var ii_show = 0
    //清空高亮
    for (let index = 0; index < children.length; index++) {
      let child = children[index]
      const data = child.getComponent(BagGrilditem)
      if (data.m_type == -1) data.setSelectBgAct(false)
    }
    //需要高亮以及可以高亮的格子有几个
    for (let j = 0; j < arr_block.length; j++) {
      if (i_node + arr_block[j] < DataMgr.BagGrid_row * DataMgr.BagGrid_column) {
        let child = children[i_node + arr_block[j]]
        const data = child.getComponent(BagGrilditem)
        if (child.getChildByName('Node').active == false) {
          ii_show++

          if ((i_node + 1) % DataMgr.BagGrid_row == 0) {
            break
          }
        }
      }
    }
    //高亮
    if (ii_show == arr_block.length) {
      //获取所有块中心位置
      let tol_posx = 0
      let tol_posy = 0

      for (let j = 0; j < arr_block.length; j++) {
        let child = children[i_node + arr_block[j]]
        // let childPosition = child.getPosition()
        let childPosition = child.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO)
        const data = child.getComponent(BagGrilditem)
        if (i_node + arr_block[j] < DataMgr.BagGrid_row * DataMgr.BagGrid_column && data.m_type == -1) {
          tol_posx += childPosition.x
          tol_posy += childPosition.y
          child.getComponent(BagGrilditem).setSelectBgAct(true)
          compSelectItem.setPosIndex.push(i_node + arr_block[j])
        }
      }
      compSelectItem.iscanPlaced = true

      // let pos = new Vec3(tol_posx / ii_show, tol_posy / ii_show, 0)
      let pos = this.bottomBgLayer
        .getComponent(UITransform)
        .convertToNodeSpaceAR(new Vec3(tol_posx / ii_show, tol_posy / ii_show, 0))

      compSelectItem.setPos = pos
    } else {
      compSelectItem.iscanPlaced = false
      compSelectItem.setPos = Vec3.ZERO
    }
    // const thisBagitem = children[i_node].getComponent(Bagitem)
    // const onGrildNode = this.ItemNodeToGrildMap.get(i_node)
    // if (!onGrildNode) return
    // const onGrildItem = onGrildNode.getComponent(SelectItem)
    // if (compSelectItem.itemType == thisBagitem.m_type) {
    //   onGrildItem.canUpgrade = true
    //   //设置透明度
    //   onGrildItem.node.getComponent(UIOpacity).opacity *= 0.2
    //   compSelectItem.iscanPlaced = true
    // } else {
    //   compSelectItem.iscanPlaced = false
    //   onGrildItem.canUpgrade = false
    //   onGrildItem.node.getComponent(UIOpacity).opacity = 1
    // }
  }
  placeEnd(Node: Node) {
    const compSelectItem = Node.getComponent(WeapItem)
    const children_block = this.bottomBgLayer.children
    let arr_block = compSelectItem.setPosIndex
    let preArr = compSelectItem.preposIndex

    // if (compSelectItem.canUpgrade) {
    //   this.ItemNodeToGrildMap.get(arr_block[0])
    //     .getComponent(SelectItem)
    //     .UpGradeData(this.m_selectItemData.get(compSelectItem.itemType))
    //   compSelectItem.canUpgrade = false
    //   compSelectItem.node.destroy()
    //   return
    // }

    //如果选择的武器已经在格子上了
    if (compSelectItem.isPlaced) {
      for (let ii = 0; ii < preArr.length; ii++) {
        const data = children_block[preArr[ii]].getComponent(BagGrilditem)
        data.addItemToGrid(-1)
        data.setSelectBgAct(false)
      }
    } else {
      compSelectItem.node.parent = this.occupyNode
      compSelectItem.isPlaced = true
    }

    for (let i = 0; i < arr_block.length; i++) {
      const data = children_block[arr_block[i]].getComponent(BagGrilditem)
      data.addItemToGrid(compSelectItem.itemType)
      preArr[i] = arr_block[i]
    }
    this.ItemNodeToGrildMap.set(arr_block[0], Node)
    Node.setPosition(compSelectItem.setPos)
    compSelectItem.startPos = Node.getPosition()
  }
  onClickUpdateSelectItem() {
    this.selectItem.removeAllChildren()
    this.createSelectItem()
  }

  MoveGrild() {
    // this.
  }

  public loadResAsync(path: string, type: typeof Asset): Promise<any> {
    if (path == '') {
      return null
    }
    return new Promise((resolve, reject) => {
      resources.load(path, type, (error: Error, resource: any) => {
        if (error) {
          reject(error)
        } else {
          console.log(`加载资源-->from res async--> ${path}`)
          resolve(resource)
        }
      })
    })
  }

  update(deltaTime: number) {}
}
